#include "UserLogin.h"
#include <QLabel>
#include "CCMainWindow.h"
#include <QBitmap>
#include <QSql>
#include <qmessagebox.h>
#include <qsqldatabase.h>
#include <QSqlQuery>

QString userA;

UserLogin::UserLogin(QWidget *parent)
	: BasicWindow(parent)
{
	ui.setupUi(this);
	setAttribute(Qt::WidgetAttribute::WA_DeleteOnClose);
	initTitleBar();
	setTitleBarTitle("", ":/Resources/MainWindow/qqlogoclassic.png");
	loadStyleSheet("UserLogin");

	initControl();
}



void UserLogin::initControl()
{
	head = new QLabel(this);
	head->setFixedSize(68, 68);
	//QPixmap(":/Resources/MainWindow/head_mask.png")
	QPixmap pixmap;
	pixmap = getRoundImage(QPixmap(":/Resources/MainWindow/app/logo.ico"),
							QPixmap(":/Resources/MainWindow/head_mask.png"),
							head->size());
	head->setPixmap(pixmap);
	head->move(width() / 2 - 34, ui.titleWidget->height() - 34);
	//head->setMask(pixmap.mask());

	connect(ui.loginBtn, SIGNAL(clicked()),
		this, SLOT(onLoginBtnClicked()));

	if (!connectMySql())
	{
		QMessageBox::warning(this, "警告", "mysql", QMessageBox::StandardButton::Ok);
		close();
	}
}

bool UserLogin::connectMySql()
{
	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

	db.setDatabaseName("qtqq");
	db.setHostName("127.0.0.1");
	db.setUserName("root");
	db.setPassword("1316");
	db.setPort(3306);

	if (db.open())
	{
		return true;
	}

	return false;
}

bool UserLogin::verifyAccountCode()
{
	QString account = ui.editUserAccount->text();
	QString password = ui.editPassword->text();

	QSqlQuery querySql;
	querySql.exec(
		QString("SELECT code FROM tab_accounts \
			WHERE account= '%1';").arg(account)
	);
	if (querySql.next()) {
		if (querySql.value(0).toString() == password)
		{	
			userA = account;
			return true;
		}
	}



	return false;
}

void UserLogin::onLoginBtnClicked()
{
	
	//SetConsoleOutputCP(CP_UTF8);
	//() << "UserLogin关闭";

	if (!verifyAccountCode())
	{
		QMessageBox::information(nullptr, "提示", 
			"账号或密码错误,请重新输入!", QMessageBox::StandardButton::Ok);

		ui.editUserAccount->setText("");
		ui.editPassword->setText("");
		return;
	}

	close();

	CCMainWindow *mainWidget = new CCMainWindow(nullptr);
	mainWidget->show();
	
	
}

UserLogin::~UserLogin()
{
	delete head;
}
